package com.example.design.factory;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shishaopeng
 * Date: 2023-10-29-01-43
 * Desc: 授权工厂交给 IOC 容器托管
 */
@Component
public class OauthServiceFactory implements ApplicationContextAware {

    private static final Map<String, OauthService> MAP = new HashMap<>(2);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OauthService> services = applicationContext.getBeansOfType(OauthService.class);
        if (MapUtils.isEmpty(services)) {
            return;
        }
        for (OauthService service : services.values()) {
            String key = this.mapKey(service.platform().getDictCode(), service.appKey());
            MAP.put(key, service);
        }
    }

    public OauthService getService(String platform, String appKey) throws Exception {
        OauthService service = MAP.get(this.mapKey(platform, appKey));
        if (service == null) {
            throw new Exception("没有相应的授权服务");
        }
        return service;
    }

    private String mapKey(String platform, String appKey) {
        return "p:" + platform + "&a:" + appKey;
    }
}
